package com.tingyuge.thinking.spring.dependency.injection;

import com.tingyuge.thinking.spring.dependency.injection.annotation.UserGroup;
import com.tingyuge.thinking.spring.ioc.overview.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;

import java.util.Collection;

/**基于注解 {@link Qualifier} 方法注入
 * @author xiaodao
 * @version 1.0
 * @date 2021/6/29
 */
public class QualifierDependencyInjectionDemo {


    @Autowired
    private User user;
    @Autowired
    @Qualifier("user")
    private User nameUser;
    //整体应用上下文, 有4个User的bean
    //SuperUser
    //user
    //User1-->@qualifier
    //User2-->@qualifier


    @Autowired
    private Collection<User> allUsers; //2 bean = SuperUser user
    @Autowired
    @Qualifier
    private Collection<User>  qualifierUsers; //4 bean == user1 user2 user3 user4

    @Autowired
    @UserGroup
    private Collection<User>  userGroupUsers; //2 bean == user1 user2

    @Bean
    @Qualifier//进行逻辑分组
    private User user1(){
        return createUser(1l);
    }
    @Bean
    @Qualifier//进行逻辑分组
    private User user2(){
        return createUser(2l);
    }

    @Bean
    @UserGroup
    public User user3(){
        return createUser(3l);
    }
    @Bean
    @UserGroup
    public User user4(){
        return createUser(4l);
    }
    private static User createUser(Long id ){
        User user= new User();
        user.setId(id);
        return user;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        //注册 configuration class（配置类）
        applicationContext.register(QualifierDependencyInjectionDemo.class);

        XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(applicationContext);
        String xmlClassPath = "classpath:/META-INF/dependency-lookup-context.xml";
        beanDefinitionReader.loadBeanDefinitions(xmlClassPath);
        //通过BeanDefinition 注册API 方式
        //启动应用上下文
        applicationContext.refresh();
        QualifierDependencyInjectionDemo demo = applicationContext.getBean(QualifierDependencyInjectionDemo.class);
        //输出primary User
        System.out.println("demo.user:"+ demo.user);
        //期待输出User
        System.out.println("demo.user:"+ demo.nameUser);
        //期待输出  supperUser  user  user1 user 2
        System.out.println("demo.allUsers:"+ demo.allUsers);
        //期待输出   user1 user 2
        System.out.println("demo.qualifierUsers:"+ demo.qualifierUsers);
        //期待输出   user1 user 2
        System.out.println("demo.userGroupUsers:"+ demo.userGroupUsers);
        //显示关闭应用上下文
        applicationContext.close();
    }
}
